package me.android.library.common.orm.ability;

import android.content.ContentValues;
import android.database.sqlite.SQLiteDatabase;

import com.google.common.collect.Lists;

import java.util.Collection;
import java.util.List;
import java.util.Map;

import me.android.library.utils.android.ContentValuesUtil;
import mylab.base.foundation.lang.Identifiable;

public interface Insert<T extends Identifiable<Long>> extends DS, EntityInfo<T> {
    default Long insert(T entity) {
        ContentValues content = ContentValuesUtil.fromBean(entity);
        return insert(content);
    }

    default Long insert(Map<String, Object> map) {
        ContentValues content = ContentValuesUtil.fromMap(map);
        return insert(content);
    }

    default Long insert(ContentValues content) {
        try (SQLiteDatabase db = writableDb()) {
            return db.insert(getTableName(), null, content);
        }
    }

    default Long[] insertBatch(Collection<T> entities) throws Exception {
        List<ContentValues> contents = Lists.newArrayList(ContentValuesUtil.fromBeans(entities));
        Long[] ids = new Long[entities.size()];
        tx(db -> {
            try {
                for (int i = 0; i < entities.size(); i++) {
                    ids[i] = db.insert(getTableName(), null, contents.get(i));
                }
            } catch (Exception e) {
                return e;
            }
            return null;
        });
        return ids;
    }

}
